import { DemoBlock } from '@/components/demos-util';
import { type DetailResult } from '@/pages/types/type';
import { checkAuthorize } from '@/utils/authorize';
import { Content, Page } from '@alita/flow';
import { setPageNavBar, useLocation, useNavigate } from 'alita';
import {
  Button,
  Card,
  DotLoading,
  Form,
  Input,
  NavBar,
  Radio,
  Space,
  Stepper,
  Toast,
} from 'antd-mobile';
import { useEffect, useRef, useState } from 'react';

import { getRequestInit, postRequestInit, urlPrefix } from '@/utils/http';
import { useModel } from 'alita';
import { AntOutline } from 'antd-mobile-icons';
import { ToastHandler } from 'antd-mobile/es/components/toast';
import styles from './index.less';
const numberFormator = new Intl.NumberFormat();
type Hospital = {
  id: number;
  name: string;
};
// type DiagnosisGroup = {
//   id: number;
//   name: string;
// };
type Department = {
  errcode: number;
  errmsg: string;
  department: {
    id: number;
    name: string;
    name_en: string;
    department_leader: string;
    parentid: number;
    order: number;
  };
};

export default () => {
  const navigate = useNavigate();
  const location = useLocation();
  //   const [searchParams, setSearchParams] = useSearchParams();
  const [tokening, setTokening] = useState<boolean>(true);
  const [tokenFail, setTokenFail] = useState<string | undefined>(undefined);
  const [authOK, setAuthOK] = useState<boolean>(false);
  const [loadFails, setLoadFails] = useState<string[]>([]);
  const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
  const [loadingTimes, setLoadingTimes] = useState<number>(0);

  // 提交时状态控制
  const [ing, setIng] = useState<boolean>();
  const [fail, setFail] = useState<string>();
  const [success, setSuccess] = useState<string>();
  const [departments, setDepartments] = useState<Department[]>([]);
  // const [hospitals, setHospitals] = useState<Hospital[]>([]);
  // const [diagnosisGroups, setDiagnosisGroups] = useState<DiagnosisGroup[]>([]);

  const handler = useRef<ToastHandler>();

  type FieldModal = {
    deviceSerialNumber: string;
    meta: string;
  };
  const [form] = Form.useForm<FieldModal>();

  const model = useModel('useAuthModel');
  useEffect(() => {
    setPageNavBar({
      pagePath: location.pathname,
      navBar: {
        hideNavBar: true,
        pageTitle: `创建诊断组`,
        pageBackground: '#eee',
      },
    });
    checkAuthorize(
      (x) => setTokening(x),
      (y) => {
        console.log(`token检查完成，是否通过授权：${y}`);
        setAuthOK(y);
      },
      (z) => setTokenFail(z),
      model,
    );
  }, []);

  function load() {
    if (authOK) {
      let times = 1;
      handler.current = Toast.show({
        icon: 'loading',
        content: '正在载入企业微信架构',
        maskClickable: false,
        duration: 0,
      });
      // 获取所有钉钉部门
      fetch(
        `${urlPrefix}/api/diagnosis-group-handle/get-department-not-match-diagnosis-group`,
        getRequestInit(),
      )
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(({ data, code, msg }: DetailResult<Department[]>) => {
                if (code === 0) {
                  if (data) {
                    setDepartments(data!);
                  }
                  setLoadOK(msg);
                  handler.current?.close();
                } else {
                  setLoadFails([...loadFails, msg]);
                  Toast.show({
                    icon: 'fail',
                    content: msg,
                    duration: 3000,
                  });
                }
              })
              .catch((reason) => {
                setLoadFails([...loadFails, reason]);
                Toast.show({
                  icon: 'fail',
                  content: `加载失败：${reason}`,
                });
              });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          setLoadFails([...loadFails, `加载部门：${reason}`]);
          Toast.show({
            icon: 'fail',
            content: `加载失败：${reason}`,
          });
        })
        .finally(() => {
          setLoadingTimes(--times);
        });
      // 全部诊断组：
    } // end if authOK
  }
  useEffect(load, [authOK]);

  const onFinish = (values: FieldModal) => {
    // Dialog.alert({
    //   content: <pre>{JSON.stringify(values, null, 2)}</pre>,
    // });
    // return;
    const url = '/api/diagnosis-group-handle/create';
    const requestInit: RequestInit = postRequestInit(values);
    let response: Promise<Response> = fetch(`${urlPrefix}${url}`, requestInit);
    response
      .then(async (rsp: Response) => {
        if (rsp.ok) {
          rsp
            .json()
            .then(async (x: DetailResult<string>) => {
              const { data, code, msg } = x;
              if (code === 0) {
                //setSuccess(msg);
                if (data!.length > 5) {
                  Toast.show(data!);
                } else {
                  Toast.show(msg);
                }
              } else {
                setFail(msg);
              }
            })
            .catch((reason) => {
              setFail(reason);
              console.error(`${url} catch in 最内层!`);
            })
            .finally(() => {
              console.log(`finally in 最内层:${url}`);
            });
        } else {
          setFail(`rsp not OK![${url}]`);
          console.log(`!!! rsp not ok! [${url}]`);
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setFail(`发生错误：${reason}[${url}]`);
        console.error(`${url} catch in 最外层`);
      })
      .finally(() => {
        setIng(false);
        console.log(`finally in 最外层:${url}`);
      });
  };

  if (tokening) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在授权...</span>
      </div>
    );
  }

  if (loadingTimes > 0) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在载入,剩余{loadingTimes}个请求...</span>
      </div>
    );
  }

  return (
    <Page>
      <Content>
        <DemoBlock padding={8}>
          <NavBar
            left={
              <Button
                color="primary"
                size="mini"
                shape="rounded"
                onClick={() => navigate('/')}
              >
                首
              </Button>
            }
            // 未定义导航栏右侧内容！
            onBack={() => navigate(-1)}
          >
            创建诊断组
          </NavBar>
        </DemoBlock>

        <Card
          title={
            <div style={{ fontWeight: 'normal' }}>
              <AntOutline style={{ marginRight: '4px', color: '#1677ff' }} />
              创建诊断组
            </div>
          }
          // extra={<RightOutline />}
          // onBodyClick={onBodyClick}
          // onHeaderClick={onHeaderClick}
          style={{ borderRadius: '16px', margin: '10px' }}
        >
          <div className={styles.content}>
            <Form
              form={form}
              layout={'vertical'}
              onFinish={onFinish}
              footer={
                <>
                  <Button
                    block
                    type="submit"
                    disabled={
                      !authOK ||
                      ing ||
                      fail !== undefined ||
                      success !== undefined
                    }
                    loading={ing}
                    color="primary"
                    size="large"
                  >
                    {success !== undefined ? '已申请' : '提交'}
                  </Button>
                </>
              }
            >
              <Form.Item
                name="departmentId"
                label={'匹配企业微信部门'}
                rules={[{ required: true, message: '企业微信部门' }]}
              >
                <Radio.Group>
                  <Space direction={'vertical'}>
                    {departments
                      .filter(
                        ({ errcode, department }) =>
                          errcode === 0 &&
                          department.name.indexOf('诊断组') >= 0,
                      )
                      .map(({ department }) => (
                        <Radio key={department.id} value={department.id}>
                          {department.name}
                        </Radio>
                      ))}
                  </Space>
                </Radio.Group>
              </Form.Item>

              <Form.Item
                name="name"
                label={'名称'}
                rules={[{ required: true, message: '名称' }]}
              >
                <Input maxLength={200} />
              </Form.Item>

              <Form.Item
                name="title"
                label={'报告标题'}
                rules={[{ required: true, message: '报告标题' }]}
              >
                <Input maxLength={200} />
              </Form.Item>

              <Form.Item
                name="price"
                label={'收费标准'}
                rules={[{ required: true, message: '收费标准' }]}
              >
                <Stepper min={0} max={100} step={1} />
              </Form.Item>
            </Form>
          </div>
        </Card>
      </Content>
    </Page>
  );
};
